package com.freely.data.adapter;

import android.util.Log;

import com.freely.data.entities.Message;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * @author DaWan
 * @time 2018/12/2 15:52
 * @dscription
 */
public class GsonMessageAdapter implements JsonDeserializer<Message> {
	private static final String TAG = "GsonMessageAdapter";

	@Override
	public Message deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		Log.d(TAG, "deserialize: "+json.toString());
		JsonObject object = json.getAsJsonObject();
		Message message = new Message();

		int messageType = object.getAsJsonPrimitive("message_type").getAsInt();
		message.setMessageType(messageType);
		if (messageType == 1 || messageType == 2) {
			long groupId = object.getAsJsonObject("group")
					.getAsJsonPrimitive("group_id")
					.getAsLong();
			message.setGroupId(groupId);
			long sender = object.getAsJsonObject("sender")
					.getAsJsonPrimitive("user_id")
					.getAsLong();
			message.setSenderId(sender);
		}

		int messageResult = object.getAsJsonPrimitive("message_result").getAsInt();
		message.setResult(messageResult);
		long receiver = object.getAsJsonObject("receiver")
				.getAsJsonPrimitive("user_id")
				.getAsLong();
		message.setReceiverId(receiver);
		String messageContent = object.getAsJsonPrimitive("message_content").getAsString();
		message.setMessageContent(messageContent);
		long messageId = object.getAsJsonPrimitive("message_id").getAsLong();
		message.setMessageId(messageId);
		boolean messageRead = object.getAsJsonPrimitive("message_read").getAsBoolean();
		message.setRead(messageRead);
		long messageSendTime = object.getAsJsonPrimitive("message_send_time").getAsLong();
		message.setMessageSendTime(new Date(messageSendTime));
		String messageTitle = object.getAsJsonPrimitive("message_title").getAsString();
		message.setMessageTitle(messageTitle);
		return message;
	}
}
